<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">















 
 
 
 
 
 
 
  
  


<html>
  <head>
    <script type="text/javascript" language="JavaScript">
    ORIGINAL_PAGE_PATH = "/appengine/docs/python/datastore/creatinggettinganddeletingdata.html";
    </script>
    
    
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Creating, Getting and Deleting Data - Google App Engine - Google Code</title>
<script type="text/javascript"><!--
(function(){function a(){this.t={};this.tick=function(c){this.t[c]=(new Date).getTime()};this.tick("start")}var b=new a;window.jstiming={Timer:a,load:b};if(window.external&&window.external.pageT)window.jstiming.pt=window.external.pageT;})();

var _tocPath_ = '/appengine/docs/_toc.ezt';
var codesite_token = null;
//--></script>
<link href="../../../../css/codesite.pack.04102009.css" type="text/css" rel="stylesheet"></link>
<script src="../../../../js/codesite_head.pack.04102009.js" type="text/javascript"></script>
<script type="text/javascript">CODESITE_CSITimer['load'].tick('bhs');</script>
<link rel="search" type="application/opensearchdescription+xml" title="Google Code" href="http://code.google.com/osd.xml" />

<!--[if IE]><link rel="stylesheet" type="text/css" href="../../../../css/iehacks.css" /><![endif]-->

    <link href="../../../../css/semantic_headers.css" rel="stylesheet" type="text/css" />
    <link href="../../../css/local_extensions.css" rel="stylesheet" type="text/css" />
  </head>

  <body class="gc-documentation">

    
    
    
</a>

<div id="gb">
 <span>
  
    <a id="lang-dropdown" class="dropdown" href="http://code.google.com" onclick="return false;"><img class="globeicon" src="../../../../images/globe2_small.png"/><span>English</span></a>
  
 </span>
</div>

<div class="gbh" style="left: 0pt;"></div>
<div class="gbh" style="right: 0pt;"></div>


<style type="text/css">
  #gc-topnav h1 {
    padding: 0 0 0 6px;
  }
</style>


<div id="gc-container">
<a name="top"></a>
<div id="skipto">
  <a href="#gc-pagecontent">Skip to page content</a>
  <a href="#gc-toc">Skip to main navigation</a>
</div>

<div id="gc-header">
  <div id="logo"><a href="http://code.google.com">
  
  
     <img src="../../../../images/cleardot.gif" height="1px" width="1px" alt="Google Code Home Page" id="gc-logo-img"/>
  
  
  </a></div>
  <div id="search">
    <div id="searchForm" class="searchForm">
      <form id="cse" action="http://www.google.com/cse" accept-charset="utf-8" class="gsc-search-box" onsubmit="executeGSearch(document.getElementById('gsearchInput').value); return false;">
      <noscript>
      <input type="hidden" name="cref" value="http://code.google.com/cse/googlecode-context.xml"/>
      </noscript>
        <table class="gsc-search-box" cellpadding="0" cellspacing="0">
          <tbody>
            <tr>
              <td class="gsc-input">
                <input id="gsearchInput" type="text" name="q" maxlength="2048" class="gsc-input" autocomplete="off" title="Google Code Search" style="width:345px"/>
              </td>
              <td class="gsc-search-button">
                <div id="cs-searchresults" onclick="event.cancelBubble = true;"></div>
                <input title="Search" id="gsearchButton" class="gsc-search-button" name="sa" value="Search" type="submit"/>
              </td>
            </tr>
            <tr>
              <td colspan="2" class="greytext">e.g. "templates" or "datastore"</td>
            </tr>
          </tbody>
        </table>
      </form>
    </div> <!-- end searchForm -->
  </div> <!-- end search -->
</div> <!-- end gc-header -->


<div id="codesiteContent">

<a name="gc-topnav-anchor"></a>
<div id="gc-topnav">
  <h1>Google App Engine</h1>
  <ul id="docs" class="gc-topnav-tabs">

    <li id="home_link">
      <a href="../../../index.html" title="Google App Engine home page">Home</a>
    </li>
  
    <li id="docs_link">
      <a href="../../index.html" class="selected" title="Official Google App Engine documentation">Docs</a>
    </li>
  
    <li id="faq_link">
      <a href="../../../kb/index.html" title="Answers to frequently asked questions about Google App Engine">FAQ</a>
    </li>
  
    <li id="articles_link">
      <a href="../../../articles/index.html" title="Focused articles and tutorials for Google App Engine developers">Articles</a>
    </li>
  
    <li>
      <a href="http://googleappengine.blogspot.com/" title="Official Google App Engine blog">Blog</a>
    </li>
  
    <li>
      <a href="../../../community.html" title="Community home for Google App Engine">Community</a>
    </li>
  
    <li>
      <a href="../../../terms.html" title="Google App Engine terms of service">Terms</a>
    </li>
  
    <li>
      <a href="../../../downloads.html" title="Download Google App Engine">Download</a>
    </li>
  

  </ul>
</div> <!-- end gc-topnav -->

    <div class="g-section g-tpl-170">

      <div class="g-unit g-first" id="gc-toc">
        <ul>
  <li><a href="../../../downloads.html">Downloads</a></li>
  <li><a href="http://code.google.com/status/appengine">System Status</a></li>
  <li><a href="http://code.google.com/p/googleappengine/issues/list">Issue Tracker</a></li>
</ul>
<div class="line"></div>
<ul>
  <li><h2>Getting Started</h2>
    <ul>
      <li><a href="../../whatisgoogleappengine.html">What Is Google App Engine?</a></li>
      <li><a href="../../java/gettingstarted/index.html">Java</a>
        <ul>
              <li><a href="../../java/gettingstarted/introduction.html">Introduction</a></li>
    <li><a href="../../java/gettingstarted/installing.html">Installing the Java SDK</a></li>
    <li><a href="../../java/gettingstarted/creating.html">Creating a Project</a></li>
    <li><a href="../../java/gettingstarted/usingusers.html">Using the Users Service</a></li>
    <li><a href="../../java/gettingstarted/usingjsps.html">Using JSPs</a></li>
    <li><a href="../../java/gettingstarted/usingdatastore.html">Using the Datastore with JDO</a></li>
    <li><a href="../../java/gettingstarted/staticfiles.html">Using Static Files</a></li>
    <li><a href="../../java/gettingstarted/uploading.html">Uploading Your Application</a></li>

        </ul>
      </li>
      <li><a href="../gettingstarted/index.html">Python</a>
        <ul>
            <li><a href="../gettingstarted/introduction.html">Introduction</a></li>
  <li><a href="../gettingstarted/devenvironment.html">The Development Environment</a></li>
  <li><a href="../gettingstarted/helloworld.html">Hello, World!</a></li>
  <li><a href="../gettingstarted/usingwebapp.html">Using the webapp Framework</a></li>
  <li><a href="../gettingstarted/usingusers.html">Using the Users Service</a></li>
  <li><a href="../gettingstarted/handlingforms.html">Handling Forms With webapp</a></li>
  <li><a href="../gettingstarted/usingdatastore.html">Using the Datastore</a></li>
  <li><a href="../gettingstarted/templates.html">Using Templates</a></li>
  <li><a href="../gettingstarted/staticfiles.html">Using Static Files</a></li>
  <li><a href="../gettingstarted/uploading.html">Uploading Your Application</a></li>

        </ul>
      </li>
    </ul>
  </li>
</ul>
<div class="line"></div>
<ul>
  <li><h2>Java <sup class="new">Early Look</sup></h2>
    <ul>
          <li><a href="../../java/overview.html">Overview</a></li>
    <li><a href="../../java/runtime.html">Servlet Environment</a></li>
    <li><a href="../../java/datastore/index.html">Storing Data</a>
      <ul>
            <li><a href="../../java/datastore/overview.html">Overview</a></li>
    <li><a href="../../java/datastore/usingjdo.html">Using JDO</a></li>
    <li><a href="../../java/datastore/dataclasses.html">Defining Data Classes</a></li>
    <li><a href="../../java/datastore/creatinggettinganddeletingdata.html">Creating, Getting and Deleting Data</a></li>
    <li><a href="../../java/datastore/queriesandindexes.html">Queries and Indexes</a></li>
    <li><a href="../../java/datastore/transactions.html">Transactions</a></li>
    <li><a href="../../java/datastore/relationships.html">Relationships</a></li>
    <li><a href="../../java/datastore/usingjpa.html">Using JPA</a></li>
    <li><a href="../../java/javadoc/com/google/appengine/api/datastore/package-summary.html">Low-level API</a></li>

      </ul>
    </li>
    <li><a href="../../java/apis.html">Services</a>
      <ul>
        <li><a href="../../java/memcache/index.html">Memcache</a>
          <ul>
                <li><a href="../../java/memcache/overview.html">Overview</a></li>
    <li><a href="../../java/memcache/usingjcache.html">Using JCache</a></li>
    <li><a href="../../java/javadoc/com/google/appengine/api/memcache/package-summary.html">Low-level API</a></li>

          </ul>
        </li>
        <li><a href="../../java/urlfetch/index.html">URL Fetch</a>
          <ul>
                <li><a href="../../java/urlfetch/overview.html">Overview</a></li>
    <li><a href="../../java/urlfetch/usingjavanet.html">Using java.net</a></li>
    <li><a href="../../java/javadoc/com/google/appengine/api/urlfetch/package-summary.html">Low-level API</a></li>

          </ul>
        </li>
        <li><a href="../../java/mail/index.html">Mail</a>
          <ul>
                <li><a href="../../java/mail/overview.html">Overview</a></li>
    <li><a href="../../java/mail/usingjavamail.html">Using JavaMail</a></li>
    <li><a href="../../java/javadoc/com/google/appengine/api/mail/package-summary.html">Low-level API</a></li>

          </ul>
        </li>
        <li><a href="../../java/images/index.html">Images</a>
          <ul>
                <li><a href="../../java/images/overview.html">Overview</a></li>
    <li><a href="../../java/javadoc/com/google/appengine/api/images/package-summary.html">API Reference</a></li>

          </ul>
        </li>
        <li><a href="../../java/users/index.html">Google Accounts</a>
          <ul>
                <li><a href="../../java/users/overview.html">Overview</a></li>
    <li><a href="../../java/javadoc/com/google/appengine/api/users/package-summary.html">API Reference</a></li>

          </ul>
        </li>
      </ul>
    </li>
    <li><a href="../../java/javadoc/index.html">Javadoc Reference</a></li>
    <li><a href="../../java/jrewhitelist.html">JRE Class White List</a></li>
    <li><a href="../../java/config/index.html">Configuration</a>
      <ul>
            <li><a href="../../java/config/webxml.html">Deployment Descriptor</a></li>
    <li><a href="../../java/config/appconfig.html">App Config</a></li>
    <li><a href="../../java/config/indexconfig.html">Index Config</a></li>
    <li><a href="../../java/config/cron.html">Scheduled Tasks</a></li>

      </ul>
    </li>
    <li><a href="../../java/tools/index.html">Tools</a>
      <ul>
            <li><a href="../../java/tools/devserver.html">Development Server</a></li>
    <li><a href="../../java/tools/uploadinganapp.html">Uploading and Managing</a></li>
    <li><a href="../../java/tools/eclipse.html">Google Plugin for Eclipse</a></li>
    <li><a href="../../java/tools/ant.html">Using Apache Ant</a></li>

      </ul>
    </li>
    <li><a href="../../java/howto/index.html">How-To</a>
      <ul>
              <li><a href="../../java/howto/unittesting.html">Unit Testing</a></li>

      </ul>
    </li>

    </ul>
  </li>
</ul>
<div class="line"></div>
<ul>
  <li><h2>Python</h2>
    <ul>
          <li><a href="../overview.html">Overview</a></li>
    <li><a href="../runtime.html">CGI Environment</a></li>
    <li><a href="index.html">Storing Data</a>
      <ul>
             <li><a href="overview.html">Overview</a></li>
     <li><a href="entitiesandmodels.html">Entities and Models</a></li>
     <li><a href="creatinggettinganddeletingdata.html">Creating, Getting and Deleting Data</a></li>
     <li><a href="keysandentitygroups.html">Keys and Entity Groups</a></li>
     <li><a href="queriesandindexes.html">Queries and Indexes</a></li>
     <li><a href="transactions.html">Transactions</a></li>
     <li><a href="typesandpropertyclasses.html">Types and Property Classes</a></li>
     <li><a href="gqlreference.html">GQL Reference</a></li>

     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="modelclass.html">Model</a></li>
         <li><a href="expandoclass.html">Expando</a></li>
         <li><a href="polymodelclass.html">PolyModel</a></li>
         <li><a href="propertyclass.html">Property</a></li>
         <li><a href="queryclass.html">Query</a></li>
         <li><a href="gqlqueryclass.html">GqlQuery</a></li>
         <li><a href="keyclass.html">Key</a></li>
         <li><a href="functions.html">Functions</a></li>
         <li><a href="exceptions.html">Exceptions</a></li>
       </ul>
     </li>

      </ul>
    </li>
    <li><a href="../apis.html">Services</a>
      <ul>
        <li><a href="../memcache/index.html">Memcache</a>
          <ul>
                 <li><a href="../memcache/overview.html">Overview</a></li>
      <li><a href="../memcache/usingmemcache.html">Using Memcache</a></li>
     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../memcache/clientclass.html">Client</a></li>
         <li><a href="../memcache/functions.html">Functions</a></li>
       </ul>
     </li>

          </ul>
        </li>
        <li><a href="../urlfetch/index.html">URL Fetch</a>
          <ul>
                 <li><a href="../urlfetch/overview.html">Overview</a></li>
     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../urlfetch/fetchfunction.html">The fetch Function</a></li>
         <li><a href="../urlfetch/responseobjects.html">Response Objects</a></li>
         <li><a href="../urlfetch/exceptions.html">Exceptions</a></li>
       </ul>
     </li>

          </ul>
        </li>
        <li><a href="../mail/index.html">Mail</a>
          <ul>
                 <li><a href="../mail/overview.html">Overview</a></li>
     <li><a href="../mail/sendingmail.html">Sending Mail</a></li>
     <li><a href="../mail/attachments.html">Attachments</a></li>
     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../mail/emailmessageclass.html">EmailMessage</a></li>
         <li><a href="../mail/emailmessagefields.html">Message Fields</a></li>
         <li><a href="../mail/functions.html">Functions</a></li>
         <li><a href="../mail/exceptions.html">Exceptions</a></li>
       </ul>
     </li>

          </ul>
        </li>
        <li><a href="../images/index.html">Images</a>
          <ul>
                 <li><a href="../images/overview.html">Overview</a></li>
     <li><a href="../images/installingPIL.html">Installing PIL</a></li>
     <li><a href="../images/usingimages.html">Using the Images API</a></li>
     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../images/imageclass.html">Image</a></li>
         <li><a href="../images/functions.html">Functions</a></li>
         <li><a href="../images/exceptions.html">Exceptions</a></li>
       </ul>
     </li>

          </ul>
        </li>
        <li><a href="../users/index.html">Google Accounts</a>
          <ul>
                 <li><a href="../users/overview.html">Overview</a></li>
     <li><a href="../users/userobjects.html">User Objects</a></li>
     <li><a href="../users/loginurls.html">Login URLs</a></li>
     <li><a href="../users/adminusers.html">Admin Users</a></li>

     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../users/userclass.html">User</a></li>
         <li><a href="../users/functions.html">Functions</a></li>
         <li><a href="../users/exceptions.html">Exceptions</a></li>
       </ul>
     </li>

          </ul>
        </li>
      </ul>
    </li>
    <li><a href="../config/index.html">Configuration</a>
      <ul>
            <li><a href="../config/appconfig.html">App Config</a></li>
    <li><a href="../config/indexconfig.html">Index Config</a></li>
    <li><a href="../config/cron.html">Scheduled Tasks</a></li>

      </ul>
    </li>
    <li><a href="../tools/index.html">Tools</a>
      <ul>
            <li><a href="../tools/devserver.html">Development Server</a></li>
    <li><a href="../tools/uploadinganapp.html">Uploading and Managing</a></li>
    <li><a href="../tools/uploadingdata.html">Uploading Data</a></li>
    <li><a href="../tools/webapp/index.html">webapp Framework</a>
      <ul>
             <li><a href="../tools/webapp/overview.html">Overview</a></li>
     <li><a href="../tools/webapp/running.html">Running the Application</a></li>
     <li><a href="../tools/webapp/requesthandlers.html">Request Handlers</a></li>
     <li><a href="../tools/webapp/requestdata.html">Request Data</a></li>
     <li><a href="../tools/webapp/buildingtheresponse.html">Building the Response</a></li>
     <li><a href="../tools/webapp/redirects.html">Redirects, Headers and Status Codes</a></li>
     

     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../tools/webapp/requestclass.html">Request</a></li>
         <li><a href="../tools/webapp/responseclass.html">Response</a></li>
         <li><a href="../tools/webapp/requesthandlerclass.html">RequestHandler</a></li>
         <li><a href="../tools/webapp/wsgiapplicationclass.html">WSGIApplication</a></li>
         <li><a href="../tools/webapp/utilmodule.html">Utility Functions</a></li>
         
       </ul>
     </li>

      </ul>
    </li>
    <li><a href="../tools/libraries.html">Third-party Libraries</a></li>

      </ul>
    </li>
    <li><a href="../howto/index.html">How-To</a>
      <ul>
              <li><a href="../howto/usinggdataservices.html">Google Data Services</a></li>

      </ul>
    </li>

    </ul>
  </li>
</ul>
<div class="line"></div>
<ul>
  <li><h2>Managing Your App</h2>
    <ul>
      <li><a href="../../theadminconsole.html">The Admin Console</a></li>
      <li><a href="../../quotas.html">Quotas</a></li>
      <li><a href="../../billing.html">Billing</a></li>
    </ul>
  </li>
</ul>
<div class="line"></div>
<ul>
  <li><h2>Resources</h2>
    <ul>
      <li><a href="../../../kb/index.html">FAQ</a></li>
      <li><a href="../../../articles/index.html">Articles</a></li>
      <li><a href="http://appengine-cookbook.appspot.com/">Cookbook</a></li>
      <li><a href="http://appgallery.appspot.com/">App Gallery</a></li>
      <li><a href="http://code.google.com/p/googleappengine/">SDK Code</a></li>
      <li><a href="http://code.google.com/p/google-app-engine-samples/">Sample Apps Code</a></li>
      <li><a href="../../../community.html">Discussion Groups</a></li>
    </ul>
  </li>
</ul>
<div class="line"></div>
<ul>
  <li><a href="../../roadmap.html">Product Roadmap</a></li>
  <li><a href="http://code.google.com/p/googleappengine/wiki/SdkReleaseNotes">Release Notes</a></li>
  <li><a href="../../revision_history.html">Revision History</a></li>
</ul>

        <a class="hidden" href="#gc-topnav-anchor">More Google App Engine resource links</a>
      </div>

      <div class="g-unit" id="gc-pagecontent">
        <h1 class="page_title">Creating, Getting and Deleting Data</h1>



<p>The datastore API represents entities as instances of model classes.  Methods of a model instance create, update and delete the entity.  Entities can be fetched from the datastore as model instances using queries or keys.</p> 

<ul>
  <li><a href="#Creating_and_Updating_an_Entity">Creating and Updating an Entity</a></li>
  <li><a href="#Getting_Entities_Using_a_Query">Getting Entities Using a Query</a></li>
  <li><a href="#Getting_an_Entity_Using_a_Key">Getting an Entity Using a Key</a></li>
  <li><a href="#Deleting_an_Entity">Deleting an Entity</a></li>
</ul>


<h2 id="Creating_and_Updating_an_Entity">Creating and Updating an Entity</h2>

<p>Instances of <a href="modelclass.html">Model</a> (and <a href="expandoclass.html">Expando</a>) classes represent datastore entities.  An application creates a new entity of a given kind by calling the constructor of the model class that corresponds with the kind.</p>

<pre class="prettyprint">
pet = Pet(name="Fluffy",
          type="cat",
          owner=users.get_current_user())
</pre>

<p>The new entity is not created in the datastore until the instance is "put" for the first time, either by calling the <a href="modelclass.html#Model_put">put()</a> method on the instance, or by passing the instance to the <a href="functions.html#put">db.put()</a> function.</p>

<pre class="prettyprint">
pet.put()

db.put(pet)
</pre>

<p>If an instance has been stored before, the put() method updates the existing entity.</p>

<p>Queries return results as model instances.  These instances can be modified and put back into the datastore.</p>

<pre class="prettyprint">
if users.get_current_user():
  user_pets = db.GqlQuery("SELECT * FROM Pet WHERE owner = :1",
                          users.get_current_user())
  for pet in user_pets:
    pet.spayed_or_neutered = True

  db.put(user_pets)
</pre>


<h2 id="Getting_Entities_Using_a_Query">Getting Entities Using a Query</h2>

<p>The datastore can execute queries across entities of a given kind.  A query can filter results using conditions that entity property values must meet, and can return the results sorted by property values.  A query can also limit the scope to entities with a given ancestor; see <a href="keysandentitygroups.html">Keys and Entity Groups</a>.</p>

<p>For a complete description of how queries work, including several things queries cannot do, see <a href="queriesandindexes.html">Queries and Indexes</a>.</p>

<p>The datastore API provides two interfaces for performing queries on entity properties: <a href="queryclass.html">Query</a>, an interface that prepares queries using methods on a query object, and <a href="queryclass.html">GqlQuery</a>, an interface that uses a SQL-like query language called GQL.</p>

<h3>The Query Interface</h3>

<p>The <a href="modelclass.html#Model_all">all()</a> method on a <a href="modelclass.html">Model</a> (or <a href="expandoclass.html">Expando</a>) class returns a <a href="queryclass.html">Query</a> object that represents a query for all entities of the corresponding kind.  The application prepares the query by calling the <a href="queryclass.html#Query_filter">filter()</a>, <a href="queryclass.html#Query_order">order()</a>, and <a href="queryclass.html#Query_ancestor">ancestor()</a> methods on the object.</p>

<pre class="prettyprint">
class Story(db.Model):
  title = db.StringProperty()
  date = db.DateTimeProperty()

query = Story.all()

query.filter('title =', 'Foo')
query.order('-date')
query.ancestor(key)

# These methods can be chained together on one line.
query.filter('title =', 'Foo').order('-date').ancestor(key)
</pre>

<h3>The GqlQuery Interface</h3>

<p>The <a href="gqlqueryclass.html">GqlQuery</a> class constructor takes a GQL query string and optional parameter bindings.  The query string specifies the kind, and the filters, sort orders and ancestor conditions.  The query string can also include a result limit and offset.</p>

<pre class="prettyprint">
# Parameters can be bound with positional arguments.
query = db.GqlQuery("SELECT * FROM Story WHERE title = :1 "
                    "AND ANCESTOR IS :2 "
                    "ORDER BY date DESC",
                    'Foo', key)

# Or, parameters can be bound with keyword arguments.
query = db.GqlQuery("SELECT * FROM Story WHERE title = :title "
                    "AND ANCESTOR IS :parent "
                    "ORDER BY date DESC",
                    title='Foo', parent=key)

# String, number and Boolean values can be literal values in the string.
query = db.GqlQuery("SELECT * FROM Story WHERE title = 'Foo' "
                    "AND ANCESTOR IS :parent "
                    "ORDER BY date DESC",
                    parent=key)
</pre>

<p>The <a href="modelclass.html#Model_gql">gql()</a> class method of a <a href="modelclass.html">Model</a> class also prepares a GqlQuery object from a string.  The string is the GQL query string with the <code>SELECT ... FROM Model</code> omitted, because this part is implied.</p>

<pre class="prettyprint">
query = Story.gql("WHERE title = :title "
                  "AND ANCESTOR IS :parent "
                  "ORDER BY date DESC",
                  title='Foo', parent=key)
</pre>

<p>Parameter bindings can be re-bound to new values using the <a href="gqlqueryclass.html#GqlQuery_bind">bind()</a> method.  An application can re-use a GqlQuery object by re-binding parameters and re-executing the query.</p>

<h3>Executing the Query and Accessing Results</h3>

<p><a href="queryclass.html">Query</a> and <a href="gqlqueryclass.html">GqlQuery</a> objects do not execute the query until the application tries to access the results.  When the application accesses results, the query is executed, and results are loaded into memory as instances of the model class for the query.  Both query classes provide two ways to execute the query and access results: the <a href="queryclass.html#Query_fetch">fetch()</a> method, and the iterator interface.</p>

<p>The fetch() method takes a maximum number of results to fetch (the limit), and an optional number of results to skip (the offset).  The method executes the query, then fetches results until it has fetched the limit or there are no more results.  Once the results are loaded into memory, it skips to the offset if one was specified, then returns the requested results as a list of model instances.  The full query is executed for each call to fetch().</p>

<p class="note"><b>Note:</b> The offset does not affect the number of results fetched from the datastore.  All results up to the limit are fetched and stored in memory.  The offset only affects what is returned by the fetch() method.</p>

<pre class="prettyprint">
results = query.fetch(10)
for result in results:
  print "Title: " + result.title
</pre>

<p>The limit and offset given to the fetch() method override any limit and offset specified in a GQL query string.</p>

<p>If the query object is used as an iterator, the query is executed with no limit or offset, the results are loaded into memory, and the value returned is an iterator over the results.  The iterator yields instances of the model class.</p>

<pre class="prettyprint">
for result in query:
  print "Title: " + result.title
</pre>

<p class="note"><b>Note:</b> The datastore returns a maximum of 1000 results in response to a query, regardless of the limit and offset used to fetch the results.  The 1000 results includes any that are skipped using an offset, so a query with more than 1000 results using an offset of 100 will return 900 results.</p>


<h2 id="Getting_an_Entity_Using_a_Key">Getting an Entity Using a Key</h2>

<p>After an entity is stored in the datastore, the entity has a unique key.  Key values are represented in the API represents as instances of the <a href="keyclass.html">Key</a> class.  The <a href="modelclass.html#Model_put">put()</a> method of a model instance and <a href="functions.html#put">db.put()</a> function return the Key of the stored entity.  After a model instance has been stored for the first time, the <a href="modelclass.html#Model_key">key()</a> method of the model instance returns the Key for the instance.</p>

<pre class="prettyprint">
entity.put()
key = entity.key()

# ...

entity = db.get(key)
</pre>

<p>A common use of a Key value is to store it as the value of a property on another entity.  The <a href="typesandpropertyclasses.html#ReferenceProperty">ReferenceProperty</a> model property class provides automatic referencing and dereferencing of model instances as keys: A model instance can be assigned to a ReferenceProperty directly, and its key will be used as the value.</p>

<pre class="prettyprint">
class PetOwner(db.Model):
  name = db.StringProperty()

class Pet(db.Model):
  name = db.StringProperty()
  owner = db.ReferenceProperty(PetOwner)

owner = PetOwner(name="Albert")
pet = Pet(name="Fluffy", owner=owner)

# This is equivalent:
pet = Pet(name="Fluffy", owner=owner.key())
</pre>

<p>Similarly, a ReferenceProperty value accessed via a property acts like its instance.  The data entity is fetched automatically, and is not fetched until it is used.</p>

<pre class="prettyprint">
pets = db.GqlQuery("SELECT * FROM Pet WHERE name = :1", "Fluffy")
pet = pets.get()

owner_name = pet.owner.name
</pre>

<p>Key values stored without the ReferenceProperty model, such as with an Expando dynamic property or a ListProperty element, do not have the automatic dereferencing behavior.</p>

<p>The <a href="functions.html#get">db.get()</a> function fetches an entity from the datastore for a Key (or list of Keys).</p>

<p>Keys can be encoded as strings for passing around outside of the application.  To convert a string-encoded key back to a Key object, the application passes the string to the <a href="keyclass.html#Key">Key</a> constructor.</p>

<pre class="prettyprint">
obj = MyModel(name="Foo")
self.response.write('&lt;a href="/view?key=%s"&gt;%s&lt;/a&gt;' % (str(obj.key()), 
                                                      obj.name()))

# ...

key_name = self.request.get('key')
obj = db.get(db.Key(key_name))
</pre>

<p class="note"><b>Note:</b> The string encoding of a Key is opaque, but not encrypted.  If your application needs keys to not be guessable, you should further encrypt the string-encoded Key before sending it to the user.</p>


<h2 id="Deleting_an_Entity">Deleting an Entity</h2>

<p>An application can delete an entity from the datastore using a model instance or a Key.  The model instance's <a href="modelclass.html#Model_delete">delete()</a> method deletes the corresponding entity from the datastore.  The <a href="functions.html#delete">delete()</a> function takes a Key or list of Keys and deletes the entity (or entities) from the datastore.</p>

<pre class="prettyprint">
q = db.GqlQuery("SELECT * FROM Message WHERE create_date < :1", earliest_date)
results = q.fetch(10)
for result in results:
  result.delete()

# or...

q = db.GqlQuery("SELECT __key__ FROM Message WHERE create_date < :1", earliest_date)
results = q.fetch(10)
db.delete(results)
</pre>

<p>Deleting an entity does not change any Key values in the datastore that may have referred to the entity.  If your application may attempt to de-reference a Key value for a deleted entity, the application should do so using <a href="functions.html#get">db.get()</a>, then test the return value before accessing properties.</p>

<p>Deleting an entity that is an ancestor for other entities does not affect the other entities.  As long as the application does not depend on the existence of the ancestor to build keys for the descendant entities, the application can still access the descendants.</p>



      </div><!-- end gc-pagecontent -->
   </div><!-- end gooey wrapper -->

    </div> <!-- end codesite content -->

<div id="gc-footer" dir="ltr">
  <div class="text">
    
      <div class="notice"><div id="notice" style="text-align: center; border: 1em 0em 1em 0em">
  Except as otherwise <a
  href="http://code.google.com/policies.html#restrictions">noted</a>,
  the content of this page is licensed under the <a rel="license"
  href="http://creativecommons.org/licenses/by/2.5/">Creative Commons
  Attribution 2.5 License</a>, and code samples are licensed under the
  <a rel="license" href="http://www.apache.org/licenses/LICENSE-2.0">Apache
  2.0 License</a>.
<!-- <rdf:RDF xmlns="http://web.resource.org/cc/" 
              xmlns:dc="http://purl.org/dc/elements/1.1/"
              xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <Work rdf:about="">
    <license rdf:resource="http://creativecommons.org/licenses/by/2.5/" />
  </Work>
  <License rdf:about="http://creativecommons.org/licenses/by/2.5/">
    <permits rdf:resource="http://web.resource.org/cc/Reproduction"/>
    <permits rdf:resource="http://web.resource.org/cc/Distribution"/>
    <requires rdf:resource="http://web.resource.org/cc/Notice"/>
    <requires rdf:resource="http://web.resource.org/cc/Attribution"/>
    <permits rdf:resource="http://web.resource.org/cc/DerivativeWorks"/>
  </License>
</rdf:RDF> -->
</div>
Java is a registered trademark of Sun Microsystems, Inc.</div>
    
    &copy;2009 Google -
    <a href="http://code.google.com">Code Home</a> -
    <a href="http://www.google.com/accounts/TOS">Terms of Service</a> -
    <a href="http://www.google.com/privacy.html">Privacy Policy</a> -
    <a href="http://code.google.com/more">Site Directory</a>
    <br /> <br />
    Google Code offered in:
    <a href="http://code.google.com/intl/en">English</a> -
    <a href="http://code.google.com/intl/es">Español</a> -
    <a href="http://code.google.com/intl/ja">日本語</a> -
    <a href="http://code.google.com/intl/ko">한국어</a> -
    <a href="http://code.google.com/intl/pt-BR">Português</a> -
    <a href="http://code.google.com/intl/ru">Pусский</a> -
    <a href="http://code.google.com/intl/zh-CN">中文(简体)</a> -
    <a href="http://code.google.com/intl/zh-TW">中文(繁體)</a>
  </div>
</div><!-- end gc-footer -->

</div><!-- end gc-containter -->

<script type="text/javascript">CODESITE_CSITimer['load'].tick('ats');</script>
<script src="../../../../js/codesite_tail.pack.04102009.js" type="text/javascript"></script>






  </body>
</html>


